package com.xqianli.bigdata.flink.source;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;

public class FileSourceApp {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment();
        String inputPath = "data/wordcount.txt";
//        String inputPath = args[0];
        DataStream<String> dataStream = env.readTextFile(inputPath);
        DataStream<Tuple2<String,Integer>> resultStream = dataStream.flatMap(new MyFlatMapper()).keyBy(item -> item.f0).sum(1);
        resultStream.print();
        env.execute();
    }


    // 自定义
    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String, Integer>> {

        @Override
        public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
            String[] words = s.split(" ");
            for (String word : words) {
                collector.collect(new Tuple2<>(word, 1));
            }
        }
    }
}
